<?php

namespace App;

use EasySwoole\EasySwoole\Core;
use EasySwoole\Http\Message\Status;
use EasySwoole\Http\Request;
use EasySwoole\Http\Response;

class ExceptionHandler
{
    public static function handle(\Throwable $exception, Request $request, Response $response): bool
    {

        go(function () use ($exception, $request) {

            $req = [
                'host' => $request->getUri()->getHost(),
                'path' => $request->getUri()->getPath(),
                'getQuery' => $request->getUri()->getQuery()
            ];

            logger_error([
                'message' => $exception->getMessage(),
                'file' => $exception->getFile(),
                'line' => $exception->getLine(),
                'trace' => $exception->getTraceAsString(),
                'request_uri' => $req,
                'request_getParsedBody' => $request->getParsedBody(),
                'request_getBody' => $request->getBody()->__toString()
            ]);

        });

        $error = [
            'code' => Status::CODE_INTERNAL_SERVER_ERROR,
            'msg' => '系统异常，请稍后尝试',
            'result' => '',
            'data' => [],
        ];

        if (Core::getInstance()->runMode() === 'dev') {
            $error['data'] = [
                'message' => $exception->getMessage(),
                'file' => $exception->getFile(),
                'line' => $exception->getLine(),
                'trace' => $exception->getTraceAsString(),
            ];
        }

        $response->withStatus(Status::CODE_INTERNAL_SERVER_ERROR);

        return $response->write(json_encode($error, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));


    }
}